import { useMemberStore } from '@/stores'

const baseURL = 'http://pcapi-xiaotuxian-front-devtest.itheima.net'

//添加拦截器
const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    //1.非https请求，自动拼接baseURL
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    //2.请求超时,默认60s
    options.timeout = 10000
    //3.添加小程序请求头标识
    options.header = {
      ...options.header,
      // 'X-Source': 'mini',
      'source-client': 'miniapp',
    }
    //4.添加token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
  code: number
  msg: string
  result: T
}
//添加类型,支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {
  //返回Promise对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      //响应成功回调
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          // 清空用户信息 跳转登录
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          // 提示错误信息
          uni.showToast({
            title: (res.data as Data<T>).msg || '请求失败',
            icon: 'none',
          })
          reject(res)
        }
      },
      fail(err) {
        uni.showToast({
          title: '请求失败,看看网络',
          icon: 'none',
        })
        reject(err)
      },
    })
  })
}
